package com.sy.textin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.url.UrlQuery;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sy.textin.constants.TextInConstants;

import java.util.HashMap;
import java.util.Map;

public class TextInUtil {


    public Map<String, String> getHeaderMap() {
        Map<String, String> map = new HashMap<>();

        map.put(TextInConstants.HEADER_APP_ID, TextInConstants.API_KEY);
        map.put(TextInConstants.HEADER_SECRET_CODE, TextInConstants.API_SECRET);
        return map;
    }


    public void idCard(byte[] imgData) {
        HttpRequest request = HttpRequest.post(TextInConstants.ID_CARD_URL);
        request.headerMap(getHeaderMap(), false);
        request.body(imgData);
        HttpResponse execute = request.execute();
        String body = execute.body();
        FileUtil.writeUtf8String(body, "E:\\test\\img\\idcard.json");
        JSONObject jsonObject = JSONUtil.parseObj(body);
        System.out.println("--------");
    }

    public void businessLicense(byte[] imgData) {
        HttpRequest request = HttpRequest.post(TextInConstants.BUSINESS_LICENSE_URL);
        request.headerMap(getHeaderMap(), false);
        request.body(imgData);
        HttpResponse execute = request.execute();
        String body = execute.body();
        FileUtil.writeUtf8String(body, "E:\\test\\img\\businessLicense.json");
    }

    public void bankCard(byte[] imgData) {
        HttpRequest request = HttpRequest.post(TextInConstants.BANK_CARD_URL);
        request.headerMap(getHeaderMap(), false);
        request.body(imgData);
        HttpResponse execute = request.execute();
        String body = execute.body();
        FileUtil.writeUtf8String(body, "E:\\test\\img\\bankCard.json");
    }

    public static String joinGetParameter(String url, Map<String, Object> map) {
        if (CollUtil.isEmpty(map)) {
            return url;
        }
        return url + "?" + UrlQuery.of(map).build(null);
    }

    public void recognizeTable(byte[] imgData, Map<String, Object> map) {
        HttpRequest request = HttpRequest.post(joinGetParameter(TextInConstants.RECOGNIZE_TABLE_URL, map));
        request.headerMap(getHeaderMap(), false);
        request.body(imgData);
        HttpResponse execute = request.execute();
        String body = execute.body();
        FileUtil.writeUtf8String(body, "E:\\UT\\data\\recognizeTable.json");
    }
}
